package com.zhutengwei.android.zuji.activity;

import android.Manifest;
import android.content.Intent;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.NavigationView;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.widget.Toolbar;
import android.view.MenuItem;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

import com.ashokvarma.bottomnavigation.BottomNavigationBar;
import com.baidu.mapapi.SDKInitializer;
import com.zhutengwei.android.zuji.R;
import com.zhutengwei.android.zuji.db.DbOpenHelper;
import com.zhutengwei.android.zuji.fragment.BaiduMapFragment;
import com.zhutengwei.android.zuji.fragment.MyTraceFragment;
import com.zhutengwei.android.zuji.model.UserModel;
import com.zhutengwei.android.zuji.tool.Constant;
import com.zhutengwei.android.zuji.tool.IsLogined;

import java.util.List;

public class MainActivity extends BaseActivity
        implements NavigationView.OnNavigationItemSelectedListener{

    private Toolbar mToolbar;
    private DrawerLayout mDrawer;
    private NavigationView mNavigationView;
    private ActionBarDrawerToggle mToggle;
    private BottomNavigationBar mBottomNavigationBar;

    private FragmentManager mFragmentManager;

    private static final int MY_PERMISSIONS_REQUEST_CALL_PHONE = 1;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //初始化地图SDK
        SDKInitializer.initialize(getApplicationContext());

        setContentView(R.layout.activity_main);

        mToolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(mToolbar);
        getSupportActionBar().setDisplayShowTitleEnabled(false);    //去掉标题

       //FAB
        initFAB();

        //初始化左侧菜单栏数据
        initLeftDrawer();

        //如果登录，显示头像，签名等
        isLogined();

        //获取权限
        getPermissions();

        //Fragment管理
        mFragmentManager = getSupportFragmentManager();
        Fragment fragment = mFragmentManager.findFragmentById(R.id.fragment_container);

        if(fragment == null){
            fragment = new BaiduMapFragment();
            mFragmentManager.beginTransaction()
                    .add(R.id.fragment_container, fragment)
                    .commit();
        }
        //创建数据库
        DbOpenHelper helper = DbOpenHelper.getInstance(this, "zuji.db");
        helper.getWritableDatabase();
    }

    private void initFAB() {
        FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if(IsLogined.isLogined(MainActivity.this, Constant.TAG, Constant.EMAIL)){
                    //TODO:登录后跳转到界面
                    startActivity(new Intent(MainActivity.this, AddZujiActivity.class));
                } else {
                    Toast.makeText(MainActivity.this, "未登录，请先登录！", Toast.LENGTH_LONG).show();
                    startActivity(new Intent(MainActivity.this, LoginActivity.class));
                }
            }
        });
    }

    private void getPermissions(){
        getPermissions(new String[]{
                Manifest.permission.ACCESS_COARSE_LOCATION,
                Manifest.permission.ACCESS_FINE_LOCATION,
                Manifest.permission.WRITE_EXTERNAL_STORAGE,
                Manifest.permission.READ_PHONE_STATE}, new GrantedListener() {
            @Override
            public void onGranted() {
                Toast.makeText(MainActivity.this, "所有的权限都被授权！", Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onDenied(List<String> deniedPermissions) {
                for (String deniedPermission : deniedPermissions) {
                    Toast.makeText(MainActivity.this, deniedPermission + " 权限没有被授权！", Toast.LENGTH_SHORT).show();

                }
            }
        });
    }

    private void initLeftDrawer(){
        mDrawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        mToggle = new ActionBarDrawerToggle(
                this, mDrawer, mToolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
        mDrawer.addDrawerListener(mToggle);
        mToggle.syncState();

        mNavigationView = (NavigationView) findViewById(R.id.nav_view);
        mNavigationView.setNavigationItemSelectedListener(this);
    }

    @Override
    public void onBackPressed() {
        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        if (drawer.isDrawerOpen(GravityCompat.START)) {
            drawer.closeDrawer(GravityCompat.START);
        } else {
            super.onBackPressed();
        }
    }



    @SuppressWarnings("StatementWithEmptyBody")
    @Override
    public boolean onNavigationItemSelected(MenuItem item) {
        // Handle navigation view item clicks here.
        int id = item.getItemId();

        if (id == R.id.nav_my) {
            // Handle the camera action
            if(IsLogined.isLogined(this, Constant.TAG, Constant.EMAIL)){
                //TODO:登录后跳转到界面
            } else {
                Toast.makeText(this, "未登录，请先登录！", Toast.LENGTH_LONG).show();
                startActivity(new Intent(MainActivity.this, LoginActivity.class));
            }
        } else if (id == R.id.nav_gallery) {
            if(IsLogined.isLogined(this, Constant.TAG, Constant.EMAIL)){
                //登录后跳转到我的足迹界面
                Fragment fragment;

                    fragment = new MyTraceFragment();
                    mFragmentManager.beginTransaction()
                            .replace(R.id.fragment_container, fragment)
                            .commit();

            } else {
                Toast.makeText(this, "未登录，请先登录！", Toast.LENGTH_LONG).show();
                startActivity(new Intent(MainActivity.this, LoginActivity.class));
            }


        } else if (id == R.id.nav_collection) {

        } else if (id == R.id.nav_top) {

        } else if (id == R.id.nav_share) {

        } else if (id == R.id.nav_sync) {

        }

        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        drawer.closeDrawer(GravityCompat.START);
        return true;
    }



    private void isLogined(){
        if(IsLogined.isLogined(this, Constant.TAG, Constant.EMAIL)){
            //
            UserModel user = IsLogined.isLoginedAndGetUser(this,
                    Constant.TAG, Constant.EMAIL);
            View headerView = mNavigationView.getHeaderView(0);
            TextView leftSignature = (TextView) headerView.findViewById(R.id.left_signature);
            String signature = user.getSignature();
            if(signature.length() < 16){
                leftSignature.setText(user.getSignature());
            } else {
                leftSignature.setTextSize(12);
                leftSignature.setText(user.getSignature());
            }
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        finish();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
//        SharedPreferences sp =
//                getSharedPreferences(Constant.TAG, Context.MODE_PRIVATE);
//        Editor editor = sp.edit();
//        editor.remove(Constant.EMAIL);
//        editor.commit();
//        finish();
    }
}


